﻿using Consul;
using Consul.AspNetCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZhaoXi.MSACommerce.Consul.ServiceDiscovery;
using ZhaoXi.MSACommerce.Consul.ServiceRegistrantion;
using ServiceConfiguration = ZhaoXi.MSACommerce.Consul.ServiceRegistrantion.ServiceConfiguration;

namespace Zhaoxi.MSACommerce.Infrastructure._Common
{
    public static class DependencyInjection
    {
        public static IServiceCollection AddInfrastructurea(this IServiceCollection services,
            IConfiguration configuration)
        {
            ConfigureConsul(services, configuration);
            return services;
        }

        private static void ConfigureConsul(IServiceCollection services, IConfiguration configuration)
        {
            var configurationSection = configuration.GetSection(key: "ServiceCheck");
            var serviceCheck = configurationSection.Get<ServiceCheckConfiguration>();
            services.Configure<ServiceConfiguration>(
                configurationSection);
            services.AddConsul();
            services.AddConsulService(serviceConfiguration =>
            {
                serviceConfiguration.ServiceAddress = new Uri(configuration["urls"] ?? configuration
                    ["applicationUrl"]);
            }, serviceCheck);

            services.AddConsulDiscovery();
        }
    }
}
